package com.fsy.Controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fsy.entities.Askers;
import com.fsy.entities.Students;
import com.fsy.entities.Userroles;
import com.fsy.service.AskersService;
import com.fsy.service.StudentsService;
import com.fsy.service.UserrolesService;
import com.fsy.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/userroles")
public class UserRolesController {
    @Resource
    private UserrolesService userrolesService;

    @Resource
    private AskersService askersService;

    @Resource
    private StudentsService studentsService;

    /**
     * 查询用户都有什么角色
     * @param uid
     * @return
     */
    @PostMapping("/selectUserrolesById")
    public List<Userroles> selectUserrolesById(Integer uid){
        return userrolesService.selectUserrolesById(uid);
    }

    /**
     * 添加用户角色
     * @param userroles
     * @return
     */
    @PostMapping("/addUserroles")
    public Map<String,Object> addUserroles(Userroles userroles){
        boolean save = userrolesService.save(userroles);
        List<Userroles> userroles1 = userrolesService.selectUserAndUserrolesAndRolesById(userroles.getUserId());
        for(Userroles u : userroles1){
            if (u.getName().equals("咨询师")){
                Askers a =new Askers();
                a.setAskerId(u.getUserId());
                a.setAskerName(u.getLoginName());
                askersService.save(a);
            }
        }
        if (save = true){
            return Result.toClient("0","设置成功");
        } else {
            return Result.toClient("0","设置失败");
        }
    }

    /**
     * 删除用户角色
     * @param userId
     * @param roleId
     * @return
     */
    @PostMapping("/deleteUserrolesById")
    public Map<String,Object> deleteUserrolesById(Integer userId,Integer roleId){
        QueryWrapper<Students> wrapper =new QueryWrapper();
        wrapper.eq("askerId",userId);
        List<Students> list = studentsService.list(wrapper);
        if (list!=null && list.size()>0){
            return Result.toClient("1","该咨询师下还有学生，不能移除该角色");
        }else {
            askersService.deleteByAskerId(userId);
        }
        int i = userrolesService.deleteUserrolesById(userId, roleId);
        if (i>0){
            return Result.toClient("0","删除成功");
        } else {
            return Result.toClient("0","删除失败");
        }
    }
}
